package com.tonyodev.fetch2fileserver.database;


import ohos.app.Context;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;
import ohos.data.resultset.ResultSet;
import ohos.data.resultset.ResultSetHook;

public  class FileResourceInfoDatabase extends  ohos.data.DatabaseHelper {
    private String TAG = "lpq " + FileResourceInfoDatabase.class.getSimpleName();
    public static final int DATABASE_VERSION = 1;

    private volatile  FileResourceInfoDao fileResourceInfoDao;
    private RdbStore rdbStore;

    /**
     *
     * @param context
     * @param namespace
     */
    public FileResourceInfoDatabase(Context context,String namespace) {
        super(context);
        init(namespace);
    }

    private void init(String namespace) {
        System.out.println(TAG + " Create sql table"+namespace);
        StoreConfig config = StoreConfig.newDefaultConfig(namespace + ".db");
        rdbStore=getRdbStore(config, DATABASE_VERSION, new RdbOpenCallback() {
            @Override
            public void onCreate(RdbStore rdbStore) {
                System.out.println(TAG + " onCreate sql table");
                StringBuffer stringBuffer=new StringBuffer();
                stringBuffer.append("CREATE TABLE IF NOT EXISTS '"+FileResourceInfo.TABLE_NAME+ "'"+
                                    "('"+FileResourceInfo.COLUMN_ID+"' LONG NOT NULL, '"
                                         +FileResourceInfo.COLUMN_LENGTH+ "'" + " LONG NOT NULL, '"
                                         +FileResourceInfo.COLUMN_FILE+ "' TEXT NOT NULL,'"
                                         +FileResourceInfo.COLUMN_NAME + "'TEXT NOT NULL,'"
                                         +FileResourceInfo.COLUMN_EXTRAS+ "'TEXT NOT NULL,'"
                                         +FileResourceInfo.COLUMN_MD5+"' " + "TEXT NOT NULL, PRIMARY KEY('"+FileResourceInfo.COLUMN_ID+"'))");
                rdbStore.executeSql(stringBuffer.toString());
            }

            @Override
            public void onUpgrade(RdbStore rdbStore, int i, int i1) {

            }
        }, new ResultSetHook() {
            @Override
            public void createHook(String s, String[] strings, ResultSet resultSet) {
                System.out.println(TAG + "   createHook  = " + s+"   resultSet = "+resultSet);
            }
        });
    }
    public FileResourceInfoDao getInstance() {
        if (fileResourceInfoDao != null) {
            return fileResourceInfoDao;
        } else {
            synchronized (FileResourceInfoDatabase.class) {
                if (fileResourceInfoDao == null) {
                    fileResourceInfoDao = new FileResourceInfoDao_Impl(rdbStore);
                }
                return fileResourceInfoDao;
            }
        }
    }
    public void close() {
        if (rdbStore.isOpen()) {
            try {
                rdbStore.close();
            } finally {

            }
        }
    }


}
